package com.fxd.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @auther fuxudong
 * @date 2021/5/1 - 19:25
 */
@Service
public class PaymentService {

    //=======服务降级========
    //正常访问，肯定OK
    public String paymentInfo_ok(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + "okid:" + id;
    }

    //延迟3秒
//    一旦调用服务方法失败并抛出了错误信息后，会自动调用该注解中指定的方法
    @HystrixCommand(fallbackMethod = "paymentInfo_timeouthandler", commandProperties = {
//            设置自身调用超时时间的峰值，峰值内可以正常运行，超过了需要有兜底的方法处理，作服务降级fallback
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String paymentInfo_timeout(Integer id) {
        try {
//            int age=101/0;
            int timeNumber = 3;
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + "timeoutid:" + id + "  8001服务器正常";
    }

    public String paymentInfo_timeouthandler(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + "paymentInfo_timeouthandler:" + id + "  8001服务器繁忙";
    }


    //========服务熔断=======
    @HystrixCommand(fallbackMethod = "pay_fallback", commandProperties = {
//            是否开启断路器
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
//            请求次数
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
//            时间范围
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
//            失败率达到多少后跳闸
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException("id 不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "调用成功" + serialNumber;

    }

    public String pay_fallback(@PathVariable("id") Integer id) {
        return "id fallback不能为负数";
    }
}
